package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.dao.ESManagerMapper;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.ESManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * @author kfzhao
 * @version 1.0
 * @className ESManagerServiceImpl
 * @description
 * @date 2021/12/27 15:04
 */
@Service
public class ESManagerServiceImpl implements ESManagerService {
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private ESManagerMapper esManagerMapper;

    @Override
    public void createMappingAndIndex() {
        // 创建索引
        elasticsearchTemplate.createIndex(SkuInfo.class);
        // 创建映射
        elasticsearchTemplate.putMapping(SkuInfo.class);
    }

    @Override
    public void importAll() {
        // 查询sku集合
        List<Sku> skuList = skuFeign.findSkuListBySpuId("all");
        if (CollectionUtils.isEmpty(skuList)) {
            // 当前没有查询到数据
            throw new RuntimeException("当前没有查询到数据，无法导入索引库");
        }
        // 有数据，将skuList转换为json
        String jsonSkuList = JSON.toJSONString(skuList);
        // 将json串转换为当前的skuInfo
        List<SkuInfo> skuInfos = JSON.parseArray(jsonSkuList, SkuInfo.class);

        for (SkuInfo skuInfo : skuInfos) {
            // 将规格信息转换为map
            Map specMap = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(specMap);
        }
        // 导入索引库
        esManagerMapper.saveAll(skuInfos);
    }

    @Override
    public void importDataBySpuId(String spuId) {
        List<Sku> skuList = skuFeign.findSkuListBySpuId(spuId);
        if (CollectionUtils.isEmpty(skuList)) {
            // 当前没有查询到数据
            throw new RuntimeException("当前没有查询到数据，无法导入索引库");
        }
        // 将集合转为json
        String jsonSkuList = JSON.toJSONString(skuList);
        List<SkuInfo> skuInfos = JSON.parseArray(jsonSkuList, SkuInfo.class);
        for (SkuInfo skuInfo : skuInfos) {
            // 将规格信息进行转换
            Map specMap = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(specMap);
        }
        // 添加索引库
        esManagerMapper.saveAll(skuInfos);
    }

    @Override
    public void delDataBySpuId(String spuId) {
        List<Sku> skuList = skuFeign.findSkuListBySpuId(spuId);
        if (CollectionUtils.isEmpty(skuList)) {
            // 当前没有查询到数据
            throw new RuntimeException("当前没有查询到数据，无法导入索引库");
        }
        for (Sku sku : skuList) {
            esManagerMapper.deleteById(Long.parseLong(sku.getId()));
        }
    }
}
